package com.wyh.blog.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Map;

@Slf4j
public class JwtUtil {
    private static Key key = Keys.hmacShaKeyFor("-sKFOkXb57ehcMrWtqTlT5y5ezIxirS9zcrINMKZVZs".getBytes(StandardCharsets.UTF_8));
    public static String genToken(Map<String, Object> claim){
        String compact = Jwts.builder()
                .setClaims(claim)
                .signWith(key)
                .compact();
        return compact;
    }

    public static Claims parseJwt(String jwt){
        //如果传入的密钥是否为空
        if (!StringUtils.hasLength(jwt)){
            return null;
        }
        Claims claims = null;
        JwtParserBuilder parserBuilder = Jwts.parserBuilder().setSigningKey(key);
        try {
            claims = parserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e){
            log.error("令牌解析错误，e: {}", jwt);
        }
        return claims;
    }
}
